import router from "./router";
import store from "./store";
// import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login", "/404"]; 
router.beforeEach(async (to, from, next) => {
  // 开启进度条
  NProgress.start();

  document.title = getPageTitle(to.meta.title);

   const hasToken = getToken(); //获取token
  if (hasToken) {
    //   console.log(hasToken);
    //  表示已经登录过了
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      // 没有id表示没获取token
      if (!store.getters.userId) {
        await store.dispatch("user/getUserInfo");
      }
      //  有 token  但是 :去的是非登录页面
      next();
    }
  } else {
    //  表示未登陆,或者登陆token过期了
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login`); //  输入 /  在  whiteList中没有   就直接回到登录页面中
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});